package com.tos.second.handler;


import com.tos.second.common.Result.Result;
import com.tos.second.common.constant.MessageConstant;
import com.tos.second.common.exception.BaseException;
import com.tos.second.utils.MailMsg;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.ConnectException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private MailMsg mailMsg;

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获添加相同员工时的数据库异常
     * @param sq
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException sq){
        String message = sq.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }
        else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLSyntaxErrorException ex) throws MessagingException {
        mailMsg.mailException("3128214884@qq.com","数据库操作失败，请管理员及时检查");
        return Result.error(MessageConstant.MYSQL_ERROR);
    }

    @ExceptionHandler
    public Result exceptionHandler(ConnectException ex) throws MessagingException {
        mailMsg.mailException("3128214884@qq.com","redis操作失败，请管理员及时检查");
        return Result.error(MessageConstant.CONNECT_ERROR);
    }


}
